<?php
namespace app\common\model;
use think\Model;

class City extends Model{
    // 读取器
    protected function getCreateTimeAttr($data){
        return date('Y-m-d', $data);
    }
    
    /**
     * 城市添加函数
     */
    public function add($data){
        $data['status'] = 1;
        $data['create_time'] = time();
        return $this->save($data);
    }
    
    /**
     * 获取一级城市
     */
    public function getNormalFirstCity(){
        $data = [
            'status' => 1,
            'parent_id' => 0,
        ];
        
        $order = [
            'id' => 'desc',
        ];
        
        return $this->where($data)->order($order)->select();
    }

    /**
     * 获取城市信息
     * @param int $parentId
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getCities($parentId = 0){
        $data = [
            'parent_id' => $parentId,
            'status' => ['neq',-1],
        ];
        $order = [
            'listoder' => 'desc',
            'id' => 'desc',
        ];
        $result = $this->where($data)->order($order)->select();
        
        return $result;
    }
    
    /**
     * 统计分类个数
     */
    public function countCity(){
        $count = $this->where('status', 1)->count();
        return $count;
    }

    /**
     * 获取非一级城市信息
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getNormalCitys() {
        $data = [
            'status' => 1,
            'parent_id' => ['gt', 0],
        ];
        $order = ['id'=>'desc'];
        return $this->where($data)
            ->order($order)
            ->select();
    }


    /**
     * 获取所有城市（数组形式）
     * @return array
     */
    public function getAllCities(){
        $citysArr = [];
        $citys = $this->getNormalFirstCity();//一级城市内容
        foreach ($citys as $city) {
            $sedcitys = $this->getCities($city->id);
            $tmp = [];
            foreach ($sedcitys as $sedcity) {
                $tmp[] = [
                    'id' => $sedcity->id,
                    'name' => $sedcity['name'],
                ];
            }
            $citysArr[$city->id] = [
                'name' => $city['name'],
                'child' => empty($tmp)?[]:$tmp,
            ];
        }
        return $citysArr;
    }
}
